package com.ajie.slimming.ui;

/**
 //                              _oo0oo_
 //                             o8888888o
 //                             88" . "88
 //                             (| -_- |)
 //                             0\  =  /0
 //                           ___/'---'\___
 //                        .' \\\|     |// '.
 //                       / \\\|||  :  |||// \\
 //                      / _ ||||| -:- |||||- \\
 //                      | |  \\\\  -  /// |   |
 //                      | \_|  ''\---/''  |_/ |
 //                      \  .-\__  '-'  __/-.  /
 //                    ___'. .'  /--.--\  '. .'___
 //                 ."" '<  '.___\_<|>_/___.' >'  "".
 //                | | : '-  \'.;'\ _ /';.'/ - ' : | |
 //                \  \ '_.   \_ __\ /__ _/   .-' /  /
 //            ====='-.____'.___ \_____/___.-'____.-'=====
 //                              '=---='
 //
 //          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 //
 //                  佛祖保佑                 永无BUG  
 */
import java.io.File;

import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.ajie.slimming.R;
import com.ajie.slimming.config.Constants;
import com.ajie.slimming.domain.SlidingMenuCallable;
import com.ajie.slimming.ui.fragment.LeftSlidingMenuFragment;
import com.ajie.slimming.ui.fragment.ResultFragment;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnOpenListener;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

public class MainActivity extends SlidingFragmentActivity implements
        OnClickListener, SlidingMenuCallable
{
    
    // Debugging
    private static final String TAG = "MainActivity";
    
    protected SlidingMenu mSlidingMenu;
    
    
    // 左侧菜单
    private Fragment mFrag;
    
    // 默认主页
    private ResultFragment mContent;
    
    private View title_view_left/* , title_view_right */;
    
    /** 屏幕常亮 */
    private PowerManager powerManager;
    
    private WakeLock wakeLock;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        initSlidingMenu();
        setContentView(R.layout.activity_main);
        initView();
    }
    
    private void initView()
    {
        
        title_view_left = findViewById(R.id.title_view_left);
        title_view_left.setOnClickListener(this);
        // title_view_right = findViewById(R.id.title_view_right);
        // title_view_right.setOnClickListener(this);
        
        powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,
                "My Lock");
        
        UMWXHandler wxHandler = new UMWXHandler(this,Constants.WX_APP_ID,Constants.WX_SECRET_ID);
		wxHandler.addToSocialSDK();
		//朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(this,Constants.WX_APP_ID,Constants.WX_SECRET_ID);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
		
		
		// 配置需要分享的相关平台
//		addWXPlatform();
		
		addQQQZonePlatform();
    }
    
    /**
     * @功能描述 : 添加QQ平台支持 QQ分享的内容， 包含四种类型， 即单纯的文字、图片、音乐、视频. 参数说明 : title, summary,
     *       image url中必须至少设置一个, targetUrl必须设置,网页地址必须以"http://"开头 . title :
     *       要分享标题 summary : 要分享的文字概述 image url : 图片地址 [以上三个参数至少填写一个] targetUrl
     *       : 用户点击该分享时跳转到的目标地址 [必填] ( 若不填写则默认设置为友盟主页 )
     * @return
     */
    private void addQQQZonePlatform() {
        String appId = "100424468";
        String appKey = "c7394704798a158208a74ab60104f0ba";
        // 添加QQ支持, 并且设置QQ分享内容的target url
//        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this,
//                appId, appKey);
//        qqSsoHandler.setTargetUrl("http://www.umeng.com/social");
//        qqSsoHandler.addToSocialSDK();

        // 添加QZone平台
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, appId, appKey);
        qZoneSsoHandler.addToSocialSDK();
    }
    
	// /**
	// * @功能描述 : 添加微信平台分享
	// * @return
	// */
//    private void addWXPlatform() {
//        // 注意：在微信授权的时候，必须传递appSecret
//        // wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
//        String appId = "wx54a0f9ad5c413d1d";
//        String appSecret = "b26e4bdcd1dd6d434c89d24543b0791d";
//        // 添加微信平台
//        UMWXHandler wxHandler = new UMWXHandler(this, appId, appSecret);
//        wxHandler.addToSocialSDK();
//
//        // 支持微信朋友圈
//        UMWXHandler wxCircleHandler = new UMWXHandler(this, appId, appSecret);
//        wxCircleHandler.setToCircle(true);
//        wxCircleHandler.addToSocialSDK();
//    }
    
  private final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    /** 微信分享朋友圈 */
    public void shareImageToCircle(String calorie){
    	 // 设置朋友圈分享的内容
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent("减肥宝测试");
        circleMedia.setTitle("减肥宝测试");
		 UMImage urlImage = new UMImage(this,R.drawable.share);
//        UMImage urlImage = new UMImage(this,
//                "http://www.umeng.com/images/pic/social/integrated_3.png");
        circleMedia.setShareMedia(urlImage);
        // circleMedia.setShareMedia(uMusic);
        // circleMedia.setShareMedia(video);
//        circleMedia.setTargetUrl("http://www.umeng.com/social");
        mController.setShareMedia(circleMedia);
        
    	mController.directShare(this, SHARE_MEDIA.WEIXIN_CIRCLE, new SnsPostListener() {
    		@Override
    		public void onStart() {
    		}
    		@Override
    		public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
    			String showText = "分享成功";
    			if (eCode != StatusCode.ST_CODE_SUCCESSED) {
    				showText = "分享失败 [" + eCode + "]";
    			}
    			Toast.makeText(MainActivity.this, showText, Toast.LENGTH_SHORT).show();
    		}
    	});
    }
    /** 微信分享朋友 */
	public void shareImageToFriend(String calorie){
		//设置微信好友分享内容
		WeiXinShareContent weixinContent = new WeiXinShareContent();
		//设置分享文字
//		weixinContent.setShareContent("盆友们，不用运动，躺着就消耗了"
//                            + calorie
//                            + "卡路里，身材越来越苗条~淘宝搜索：imeiga塑身仪，加入我的团队，大家一起来PK吧~ ^_^");
//		//设置title
//		weixinContent.setTitle("友盟社会化分享组件-微信");
//		//设置分享内容跳转URL
//		weixinContent.setTargetUrl("你的URL链接");
//		UMImage localImage = new UMImage(this,new File(SlimmingApplication.getImageRootDir()+ "/share.png"));
		 UMImage localImage = new UMImage(this,R.drawable.share);
//	        UMImage localImage = new UMImage(this,
//	                "http://www.umeng.com/images/pic/social/integrated_3.png");
//		 UMImage localImage = new UMImage(this,R.drawable.ic_launcher);
		//设置分享图片
		weixinContent.setShareImage(localImage);
		mController.setShareMedia(weixinContent);
		mController.directShare(this, SHARE_MEDIA.WEIXIN, new SnsPostListener() {
            @Override
            public void onStart() {
            }
            @Override
            public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
                String showText = "分享成功";
                if (eCode != StatusCode.ST_CODE_SUCCESSED) {
                    showText = "分享失败 [" + eCode + "]";
                }
                Toast.makeText(MainActivity.this, showText, Toast.LENGTH_SHORT).show();
            }
        });
	}
	
	public void shareImageToQZone(String calorie){
		
		// 设置QQ空间分享内容
        QZoneShareContent qzone = new QZoneShareContent();
        qzone.setShareContent("减肥宝分享");
//        qzone.setTargetUrl("http://www.umeng.com");
        qzone.setTitle("减肥宝分享测试");
		 UMImage urlImage = new UMImage(this,R.drawable.share);
//        UMImage urlImage = new UMImage(this,
//                "http://www.umeng.com/images/pic/social/integrated_3.png");
        qzone.setShareMedia(urlImage);
//        qzone.setShareMedia(uMusic);
        mController.setShareMedia(qzone);
        
		mController.directShare(this, SHARE_MEDIA.QZONE, new SnsPostListener() {
			@Override
			public void onStart() {
			}
			@Override
			public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
				String showText = "分享成功";
				if (eCode != StatusCode.ST_CODE_SUCCESSED) {
					showText = "分享失败 [" + eCode + "]";
				}
				Toast.makeText(MainActivity.this, showText, Toast.LENGTH_SHORT).show();
			}
		});
	}
	
    // 初始化左侧菜单
    private void initSlidingMenu()
    {
        mContent = new ResultFragment();
        mFrag = new LeftSlidingMenuFragment();
        
        setBehindContentView(R.layout.main_left_layout);// 设置左边的菜单布局
        // 设置 SlidingMenu 内容
        FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction();
        // 设置左边菜单的fragment
        mFragmentTransaction.replace(R.id.main_left_fragment, mFrag);
        // 设置首页的默认fragment
        mFragmentTransaction.replace(R.id.content_frame, mContent);
        // 提交
        mFragmentTransaction.commit();
        
        mSlidingMenu = getSlidingMenu();
        mSlidingMenu.setMode(SlidingMenu.LEFT);// 设置是左滑还是右滑，还是左右都可以滑，我这里只做了左滑
        mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);// 设置菜单宽度
        mSlidingMenu.setFadeDegree(0.35f);// 设置淡入淡出的比例
        // 设置SlidingMenu 的手势模式
        // TOUCHMODE_FULLSCREEN 全屏模式，在整个content页面中，滑动，可以打开SlidingMenu
        // TOUCHMODE_MARGIN
        // 边缘模式，在content页面中，如果想打开SlidingMenu,你需要在屏幕边缘滑动才可以打开SlidingMenu
        // TOUCHMODE_NONE 不能通过手势打开SlidingMenu
        mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);// 设置手势模式
        mSlidingMenu.setShadowDrawable(R.drawable.shadow);// 设置左菜单阴影图片
        mSlidingMenu.setShadowWidthRes(R.dimen.shadow_width); // 设置阴影图片的宽度
        mSlidingMenu.setFadeEnabled(true);// 设置滑动时菜单的是否淡入淡出
        mSlidingMenu.setBehindScrollScale(0.333f);// 设置滑动时拖拽效果
        mSlidingMenu.setOnOpenListener(new OnOpenListener()
        {
            @Override
            public void onOpen()
            {
                
            }
        });
        // mContent.setSlidingMenuCallable(this);
    }
    
    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.title_view_left:
                mSlidingMenu.showMenu(true);
                break;
            default:
                break;
        }
        
    }
    
    Fragment oldFragment;
    
    /**
     * 左侧菜单点击切换首页的内容
     */
    public void switchContent(Fragment fragment)
    {
        if (oldFragment == null)
        {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.content_frame, fragment)
                    .commit();
        }
        else if (!TextUtils.equals(oldFragment.getClass().getSimpleName(),
                fragment.getClass().getSimpleName()))
        {
            getSupportFragmentManager().beginTransaction()
                    .addToBackStack(oldFragment.getClass().getSimpleName())
                    .add(R.id.content_frame, fragment)
                    .commit();
        }
        oldFragment = fragment;
        switchContent();
    }
    
    /**
     * 左侧菜单点击切换首页的内容
     */
    public void switchContent()
    {
        getSlidingMenu().showContent();
    }
    
    private long mExitTime;
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if ((System.currentTimeMillis() - mExitTime) > 2000)
            {
                mExitTime = System.currentTimeMillis();
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            }
            else
            {
                android.os.Process.killProcess(android.os.Process.myPid());
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    @Override
    protected void onResume()
    {
        super.onResume();
        wakeLock.acquire();
    }
    
    @Override
    protected void onPause()
    {
        super.onPause();
        wakeLock.release();
    }
    
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }
    
    @Override
    public void prepare(boolean isSlidingMenu)
    {
        if (isSlidingMenu)
        {
            mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);// 禁止滑动
        }
        else
        {
            mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);// 设置手势模式
        }
    }
}
